﻿using HttpApiGateway.Collect;
using HttpApiGateway.Interface;
using HttpApiGateway.Model;
using RpcHelper;
using System;
using System.Reflection;

namespace HttpApiGateway.Service
{
    internal class ApiRouteService
    {
        private bool _RegRoute(IApiController api, MethodInfo method, RouteSet set)
        {
            IApiModular modular = ApiModularCollect.Sync(method.DeclaringType);
            using (IResourceCollect resource = ResourceCollect.Create(modular))
            {
                return ApiRouteCollect.RegApi(api, modular, method, set, resource.RegRoute);
            }
        }
        private bool _RegRoute(MethodInfo method, RouteSet set)
        {
            IApiModular modular = ApiModularCollect.Sync(method.DeclaringType);
            using (IResourceCollect resource = ResourceCollect.Create(modular))
            {
                return ApiRouteCollect.RegApi(modular, method, set, resource.RegRoute);
            }
        }
    
       
        public bool Remove(MethodInfo method)
        {
            return ApiRouteCollect.Remove(method);
        }
    
        public bool RegApi(MethodInfo method, RouteSet set)
        {
            Type type = method.DeclaringType;
            if (UnityCollect.AddApi(type))
            {
                IApiController api = UnityCollect.GetApi(type);
                return this._RegRoute(api, method, set);
            }
            else if (UnityCollect.AddGateway(type))
            {
                return this._RegRoute(method, set);
            }
            else
            {
                throw new ErrorException("rpc.gateway.interface.no.find");
            }
        }
    }
}
